﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Transfer;
using DevExpress.XtraEditors;
using BranchOfSansar.Sansar.Enquiry;
using System.Collections.Generic;

namespace BranchOfSansar.Register.Trans
{
    public partial class frmTransactionList : Form
    {
        #region Form methods
        public frmTransactionList()
        {
            InitializeComponent();
        }

        public frmTransactionList(long contract_no):this()
        {
            txtContractNo.Text = contract_no.ToString();
            btnSearch_Click(null, null);
        }


        private void frmTransactionList_Load(object sender, EventArgs e)
        {
            txtDate1.DateTime = Globals.SystemDate.AddDays(-1);
            txtDate2.DateTime = Globals.SystemDate;            
            if (File.Exists(this.Name + ".xml"))
            {
                viewTransaction.RestoreLayoutFromXml(this.Name + ".xml");
                
            }
            using (EnquiryClient ec = new EnquiryClient(Globals.Token))
            {
                var cat = ec.TransferCategorys().ToList();                
                var sat = ec.TransferStatus().ToList();
                var emp = ec.Users("it.PositionNo=='E' ").ToList();
                var bank = ec.Banks().ToList();   
                var type=ec.TransferTypes().ToList();

                type.Insert(0,new ComboItem(){ Display="[Гүйлгээний төрөл]", IntValue=-1});
                txtType.Properties.Items.AddRange(type);
                txtType.SelectedIndex=0;

                bank.Insert(0, new ComboItem() { Display = "[Банк]", IntValue = -1 });
                txtBank.Properties.Items.AddRange(bank);
                txtBank.SelectedIndex = 0;

                sat.Insert(0,new ComboItem(){ IntValue=-1, Display="[Төлөв]"  });
                txtStatus.Properties.Items.AddRange(sat);
                txtStatus.SelectedIndex = 0;

                cat.Insert(0, new ComboItem() { StrValue = "", Display = "[Хэлбэр]" });
                txtCategory.Properties.Items.AddRange(cat);
                txtCategory.SelectedIndex = 0;

                List<ComboItem> usr = new List<ComboItem>();
                usr.Add(new ComboItem() { IntValue = -1, Display = "[Ажилтан]" });
                usr.AddRange(emp.Select(s => new ComboItem() { Display = s.Name, IntValue = s.UserId }).ToArray());
                txtUserNo.Properties.Items.AddRange(usr);
                txtUserNo.SelectedIndex = 0;

            }
      
        }


        private void frmTransactionList_FormClosing(object sender, FormClosingEventArgs e)
        {
            viewTransaction.SaveLayoutToXml(this.Name + ".xml");
        }

        #endregion

        #region Private methods
        private string GetQuery()
        {
            StringBuilder build = new StringBuilder(500);
            if (!string.IsNullOrWhiteSpace(txtJrNo.Text))
                build.Append(" AND it.JrNo=" + txtJrNo.Text);

            if (!string.IsNullOrWhiteSpace(txtTransNo.Text))
                build.Append(" AND it.TransNo=" + txtTransNo.Text);

            if (!string.IsNullOrEmpty(txtDate1.Text))
                build.Append(string.Format(" AND it.TxnDate>= DateTime'{0} 00:00'", txtDate1.DateTime.ToString("yyyy-M-d")));

            if (!string.IsNullOrEmpty(txtDate2.Text))
                build.Append(string.Format(" AND it.TxnDate<= DateTime'{0} 23:59'", txtDate2.DateTime.ToString("yyyy-M-d")));

            if (!string.IsNullOrEmpty(txtAmount1.Text))
                build.Append(string.Format(" AND it.TxnAmount>={0} ", txtAmount1.Text));

            if (!string.IsNullOrEmpty(txtAmount2.Text))
                build.Append(string.Format(" AND it.TxnAmount<={0} ", txtAmount2.Text));

            if (!string.IsNullOrEmpty(txtContractNo.Text))
                build.Append(string.Format(" AND it.ContractNo={0} ", txtContractNo.Text));

            if (txtUserNo.SelectedIndex > 0)
                build.Append(string.Format(" AND it.UserNo={0} ", ((ComboItem)txtUserNo.SelectedItem).IntValue));

            if (txtStatus.SelectedIndex > 0)
                build.Append(string.Format(" AND it.Status={0} ", ((ComboItem)txtStatus.SelectedItem).IntValue));

            if (txtType.SelectedIndex > 0)
                build.Append(string.Format(" AND it.TxnType={0} ", ((ComboItem)txtType.SelectedItem).IntValue));

            if (txtCategory.SelectedIndex > 0)
                build.Append(string.Format(" AND it.TxnCategory='{0}' ", ((ComboItem)txtCategory.SelectedItem).StrValue));

            if (txtBank.SelectedIndex > 0)
                build.Append(string.Format(" AND it.BankNo={0} ", ((ComboItem)txtBank.SelectedItem).IntValue));


            var res = build.ToString();
            if (res.Length < 6)
                return "";
            else
                return res.ToString().Substring(5, res.Length - 5);
        }
        private void Bind()
        {
            using (TransferClient tr = new TransferClient(Globals.Token))
            {
                gridTransaction.DataSource = tr.TransactionList(GetQuery());               
            }
        }

        #endregion

 
        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridTransaction.ShowRibbonPrintPreview();            
        }

        private void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Title = "Specify Destination Filename";
            dialog.Filter = "excell Files|*.xls";
            dialog.FilterIndex = 1;
            dialog.OverwritePrompt = true;
            dialog.CreatePrompt = true;

            if (dialog.ShowDialog() == DialogResult.OK & !string.IsNullOrEmpty(dialog.FileName))
            {
                gridTransaction.ExportToXls(dialog.FileName);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Bind();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            HyperLinkEdit link = (HyperLinkEdit)sender;
            var list = ((vw_Transaction[])gridTransaction.DataSource);
            long t=long.Parse(link.Text);
            var item=list.FirstOrDefault(w => w.TransNo == t);
            if (item.Status == 0 || item.TxnType==9999)
            {
                Globals.Warr("Буцаах боломжгүй гүйлгээ!");
                return;
            }
            
            frmTransDelete frm = new frmTransDelete(item);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                Bind();
        }

        private void txtContractNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BranchOfSansar.Register.Main.frmContractList frm = new BranchOfSansar.Register.Main.frmContractList(true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtContractNo.Text = frm.Contract.ContractNo.ToString();
                txtContractDetail.Text = string.Format("{0} байр {1} тоот", frm.Contract.ApartNo1, frm.Contract.DoorNo);
            }
        }

        private void txtCategory_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}
